package com.guli.auth.service.impl;

import com.guli.auth.feign.MemberFeign;
import com.guli.auth.feign.SmsFeign;
import com.guli.auth.service.LoginService;
import com.guli.auth.vo.UserLoginVo;
import com.guli.auth.vo.UserRegisterVo;
import com.guli.common.constant.SmsConstant;
import com.guli.common.to.SmsCode;
import com.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author zzb
 * @Date 2024/5/29 16:07
 * @Version 1.0
 * @description
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SmsFeign smsFeign;
    @Autowired
    private MemberFeign memberFeign;

    @Override
    public Boolean sendCode(String phone) {
        //获取当前系统时间
        String s = stringRedisTemplate.opsForValue().get(SmsConstant.SMS_CODE + phone);
        if (!StringUtils.isEmpty(s)) {
            //不为空，说明缓存中有数据
            String[] str = s.split("_");
            long parseLong = Long.parseLong(str[1]);
            if (System.currentTimeMillis() - parseLong < 60000) {
                /*return R.error("请勿在60s内重复获取验证码");*/
            }
        }
        //Redis保存验证码
        String substring = Long.valueOf(System.currentTimeMillis()).toString().substring(0, 5);
        SmsCode smsCode = new SmsCode();
        smsCode.setCode(substring);
        System.out.println("验证码为" + substring);
        smsCode.setPhone(phone);
        stringRedisTemplate.opsForValue().set("sms:code" + phone, substring + "_"
                + System.currentTimeMillis(), 60, TimeUnit.SECONDS);
        R code = smsFeign.code(smsCode);
        return true;
    }


    @Override
    public String register(UserRegisterVo registerVo, BindingResult result, RedirectAttributes redirectAttributes) {
        //校验数据是否符合要求
        if (result.hasErrors()) {
            Map<String, String> errors;
            errors = result.getFieldErrors().stream().collect
                    (Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页面
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //校验数据符合要求
        String code = registerVo.getCode();
        String json = stringRedisTemplate.opsForValue().get(SmsConstant.SMS_CODE + registerVo.getPhone());
        if (!StringUtils.isEmpty(json)) {
            String[] strings = json.split("_");
            String correctCode = strings[0];
            if (!code.equals(correctCode)) {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            //验证码通过
            R regist = memberFeign.regist(registerVo);
            Integer code1 = (Integer) regist.get("code");
            if (code1 == 0) {
                //删除验证码
                stringRedisTemplate.delete("sms:code" + registerVo.getPhone());
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                //有异常
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }
        Map<String, String> errors = new HashMap<>();
        errors.put("code", "验证码已过期");
        redirectAttributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/reg.html";
    }

    @Override
    public String login(UserLoginVo userLoginVo, HttpSession session) {
        R login = memberFeign.login(userLoginVo);
        if ((Integer) login.get("code") == 0) {
            session.setAttribute("loginUser", login.get("data"));
            log.info("{} => 登录成功", userLoginVo.getLoginacct());
            //远程登录
            return "redirect:http://gulimall.com";
        } else {
            //登录失败
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
